<?php

namespace app\shop\model\plus\invitationgift;

use app\common\model\plus\invitationgift\InvitationGift as InvitationGiftModel;
use app\common\exception\BaseException;

/**
 * 邀请有礼模型
 */
class InvitationGift extends InvitationGiftModel
{
    /**
     * 获取列表
     * @param $data
     */
    public function getList($data)
    {
        $model = $this;
        //检索活动名称
        if ($data['search'] != '') {
            $model = $model->where('name', 'like', '%' . trim($data['search']) . '%');
        }
        if (isset($data['status']) && $data['status']) {
            if ($data['status'] == 1) {
                $model = $model->where('start_time', '>', time())->where('status', '=', 0);
            } elseif ($data['status'] == 2) {
                $model = $model->where('start_time', '<', time())->where('end_time', '>', time())->where('status', '=', 0);
            } elseif ($data['status'] == 3) {
                $model = $model->where('end_time', '<', time())->where('status', '=', 0);
            } else {
                $model = $model->where('status', '=', 1);
            }
        }
        if (isset($data['create_time']) && $data['create_time']) {
            $model = $model->where('start_time', '>=', strtotime($data['create_time'][0]))
                ->where('end_time', '<=', strtotime($data['create_time'][1]) + 86399);
        }
        $list = $model->where('is_delete', '=', 0)
            ->order('create_time', 'desc')
            ->paginate($data);
        foreach ($list as $k => $val) {
            if ($val['start_time']['value'] > time()) {
                $list[$k]['text'] = '未开始';
            }
            if ($val['end_time']['value'] < time()) {
                $list[$k]['text'] = '已结束';
            }
            if ($val['start_time']['value'] < time() && $val['end_time']['value'] > time()) {
                $list[$k]['text'] = '进行中';
            }
        }
        return $list;
    }

    /**
     * 保存
     */
    public function add($data)
    {
        if (strtotime($data['start_time']) > strtotime($data['end_time'])) {
            $this->error = '结束时间不能小于开始时间';
            return false;
        }
        //判断是否存在重复活动
        $timeInfo = $this->where('is_delete', '=', 0)
            ->where(function ($query) use ($data) {
                $query->where(function ($query) use ($data) {
                    $query->where('start_time', '<=', strtotime($data['start_time']))
                        ->where('end_time', '>=', strtotime($data['start_time']));
                })
                    ->whereOr(function ($query) use ($data) {
                        $query->where('start_time', '>=', strtotime($data['start_time']))
                            ->where('start_time', '<=', strtotime($data['end_time']));
                    });
            })
            ->order('start_time asc')
            ->find();
        if ($timeInfo) {
            $this->error = $timeInfo['start_time']['text'] . '至' . $timeInfo['end_time']['text'] . '已有活动';
            return false;
        }
        $this->startTrans();
        try {
            $this->save($this->getSaveData($data));
            $arr1 = [];
            foreach ($data['reward_data'] as $val) {
                $arr1[] = [
                    'invitation_gift_id' => $this->invitation_gift_id,
                    'invitation_num' => $val['invitation_num'],
                    'is_point' => $val['is_point'],
                    'point' => $val['point'],
                    'is_coupon' => $val['is_coupon'],
                    'coupon' => isset($val['coupon']) ? $val['coupon'] : '',
                    'app_id' => self::$app_id,
                    'is_balance' => $val['is_balance'],
                    'balance' => $val['balance'],
                    'reward_type' => 0
                ];
            }
            //会员奖励
            $member_reward = $data['member_reward'];
            if ($data['inv_member'] && $member_reward) {
                $arr1[] = [
                    'invitation_gift_id' => $this->invitation_gift_id,
                    'invitation_num' => 0,
                    'is_point' => $member_reward['is_point'],
                    'point' => $member_reward['point'],
                    'is_coupon' => $member_reward['is_coupon'],
                    'app_id' => self::$app_id,
                    'is_balance' => $member_reward['is_balance'],
                    'balance' => $member_reward['balance'],
                    'coupon' => isset($member_reward['coupon']) ? $member_reward['coupon'] : '',
                    'reward_type' => 1
                ];
            }
            //会员消费奖励
            $consumption_reward = $data['consumption_reward'];
            if ($data['inv_consumption'] && $consumption_reward) {
                $arr1[] = [
                    'invitation_gift_id' => $this->invitation_gift_id,
                    'invitation_num' => 0,
                    'is_point' => $consumption_reward['is_point'],
                    'point' => $consumption_reward['point'],
                    'is_coupon' => $consumption_reward['is_coupon'],
                    'app_id' => self::$app_id,
                    'is_balance' => $consumption_reward['is_balance'],
                    'balance' => $consumption_reward['balance'],
                    'coupon' => isset($consumption_reward['coupon']) ? $consumption_reward['coupon'] : '',
                    'reward_type' => 2
                ];
            }
            $model = new InvitationReward();
            $model->saveAll($arr1);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 修改
     */
    public function edit($data)
    {
        if (strtotime($data['start_time']) > strtotime($data['end_time'])) {
            $this->error = '结束时间不能小于开始时间';
            return false;
        }
        //判断是否存在重复活动
        $timeInfo = $this->where('invitation_gift_id', '<>', $data['invitation_gift_id'])
            ->where('is_delete', '=', 0)
            ->where(function ($query) use ($data) {
                $query->where(function ($query) use ($data) {
                    $query->where('start_time', '<=', strtotime($data['start_time']))
                        ->where('end_time', '>=', strtotime($data['start_time']));
                })
                    ->whereOr(function ($query) use ($data) {
                        $query->where('start_time', '>=', strtotime($data['start_time']))
                            ->where('start_time', '<=', strtotime($data['end_time']));
                    });
            })
            ->order('start_time asc')
            ->find();
        if ($timeInfo) {
            $this->error = $timeInfo['start_time']['text'] . '至' . $timeInfo['end_time']['text'] . '已有活动';
            return false;
        }
        $this->startTrans();
        try {
            $update = $this->getSaveData($data);
            $this->where('invitation_gift_id', '=', $data['invitation_gift_id'])->save($update);
            $updateData = [];
            $saveData = [];
            $rewardId = [];
            foreach ($data['reward_data'] as $val) {
                if (isset($val['invitation_reward_id']) && $val['invitation_reward_id']) {
                    $updateData[] = [
                        'data' => [
                            'invitation_gift_id' => $data['invitation_gift_id'],
                            'invitation_num' => $val['invitation_num'],
                            'is_point' => $val['is_point'],
                            'point' => $val['point'],
                            'is_coupon' => $val['is_coupon'],
                            'app_id' => self::$app_id,
                            'is_balance' => $val['is_balance'],
                            'balance' => $val['balance'],
                            'coupon' => isset($val['coupon']) ? $val['coupon'] : '',
                            'reward_type' => 0
                        ],
                        'where' => [
                            'invitation_reward_id' => $val['invitation_reward_id'],
                        ],
                    ];
                    $rewardId[] = $val['invitation_reward_id'];
                } else {
                    $saveData[] = [
                        'invitation_gift_id' => $data['invitation_gift_id'],
                        'invitation_num' => $val['invitation_num'],
                        'is_point' => $val['is_point'],
                        'point' => $val['point'],
                        'is_coupon' => $val['is_coupon'],
                        'app_id' => self::$app_id,
                        'is_balance' => $val['is_balance'],
                        'balance' => $val['balance'],
                        'coupon' => isset($val['coupon']) ? $val['coupon'] : '',
                        'reward_type' => 0
                    ];
                }
            }
            //会员奖励
            $member_reward = $data['member_reward'];
            if ($data['inv_member'] && $member_reward) {
                if (isset($member_reward['invitation_reward_id']) && $member_reward['invitation_reward_id']) {
                    $updateData[] = [
                        'data' => [
                            'invitation_gift_id' => $data['invitation_gift_id'],
                            'invitation_num' => 0,
                            'is_point' => $member_reward['is_point'],
                            'point' => $member_reward['point'],
                            'is_coupon' => $member_reward['is_coupon'],
                            'app_id' => self::$app_id,
                            'is_balance' => $member_reward['is_balance'],
                            'balance' => $member_reward['balance'],
                            'coupon' => isset($member_reward['coupon']) ? $member_reward['coupon'] : '',
                            'reward_type' => 1
                        ],
                        'where' => [
                            'invitation_reward_id' => $member_reward['invitation_reward_id'],
                        ],
                    ];
                } else {
                    $saveData[] = [
                        'invitation_gift_id' => $data['invitation_gift_id'],
                        'invitation_num' => 0,
                        'is_point' => $member_reward['is_point'],
                        'point' => $member_reward['point'],
                        'is_coupon' => $member_reward['is_coupon'],
                        'app_id' => self::$app_id,
                        'is_balance' => $member_reward['is_balance'],
                        'balance' => $member_reward['balance'],
                        'coupon' => isset($member_reward['coupon']) ? $member_reward['coupon'] : '',
                        'reward_type' => 1
                    ];
                }
            }
            //会员消费奖励
            $consumption_reward = $data['consumption_reward'];
            if ($data['inv_consumption'] && $consumption_reward) {
                if (isset($consumption_reward['invitation_reward_id']) && $consumption_reward['invitation_reward_id']) {
                    $updateData[] = [
                        'data' => [
                            'invitation_gift_id' => $data['invitation_gift_id'],
                            'invitation_num' => 0,
                            'is_point' => $consumption_reward['is_point'],
                            'point' => $consumption_reward['point'],
                            'is_coupon' => $consumption_reward['is_coupon'],
                            'app_id' => self::$app_id,
                            'is_balance' => $consumption_reward['is_balance'],
                            'balance' => $consumption_reward['balance'],
                            'coupon' => isset($consumption_reward['coupon']) ? $consumption_reward['coupon'] : '',
                            'reward_type' => 2
                        ],
                        'where' => [
                            'invitation_reward_id' => $consumption_reward['invitation_reward_id'],
                        ],
                    ];
                } else {
                    $saveData[] = [
                        'invitation_gift_id' => $data['invitation_gift_id'],
                        'invitation_num' => 0,
                        'is_point' => $consumption_reward['is_point'],
                        'point' => $consumption_reward['point'],
                        'is_coupon' => $consumption_reward['is_coupon'],
                        'app_id' => self::$app_id,
                        'is_balance' => $consumption_reward['is_balance'],
                        'balance' => $consumption_reward['balance'],
                        'coupon' => isset($consumption_reward['coupon']) ? $consumption_reward['coupon'] : '',
                        'reward_type' => 2
                    ];
                }

            }
            $saveData && (new InvitationReward())->saveAll($saveData);
            $updateData && (new InvitationReward())->updateAll($updateData);
            $rewardId && (new InvitationReward())->where('invitation_reward_id', 'not in', $rewardId)
                ->where('reward_type', '=', 0)
                ->where('invitation_gift_id', '=', $data['invitation_gift_id'])
                ->delete();
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    private function getSaveData($data)
    {
        return [
            'name' => $data['name'],
            'inv_condition' => $data['inv_condition'],
            'start_time' => strtotime($data['start_time']),
            'end_time' => strtotime($data['end_time'])+86399,
            'app_id' => self::$app_id,
            'image_id' => $data['image_id'],
            'is_show' => $data['is_show'],
            'share_image_id' => $data['share_image_id'],
            'share_title' => $data['share_title'],
            'share_desc' => $data['share_desc'],
            'rule_id' => $data['rule_id'],
            'inv_type' => $data['inv_type'],
            'inv_rule' => $data['inv_rule'],
            'inv_member' => $data['inv_member'],
            'inv_consumption' => $data['inv_consumption'],
            'inv_image_id' => $data['inv_image_id']
        ];
    }

    //更新活动状态
    private function updateShow($invitation_gift_id)
    {
        $this->where('invitation_gift_id', '<>', $invitation_gift_id)->update(['is_show' => 0]);
    }

    /**
     * 发布
     */
    public function send($id)
    {
        return $this->where('invitation_gift_id', '=', $id)->update(['status' => 0]);
    }

    /**
     * 终止
     */
    public function end($id)
    {
        return $this->where('invitation_gift_id', '=', $id)->update(['status' => 1]);
    }

    /**
     * 删除
     */
    public function del($id)
    {
        return $this->where('invitation_gift_id', '=', $id)->update(['is_delete' => 1]);
    }

    /**
     * 后去数据
     */
    public function getDatas($id)
    {
        $data = $this->with(['reward', 'image', 'share', 'rule', 'invImage', 'mreward', 'creward'])->where('invitation_gift_id', '=', $id)->find();
        if (empty($data)) {
            throw new BaseException(['msg' => '没有相关信息']);
        }
        $data = $data->toArray();
        $data['start_time'] = $data['start_time']['text'];
        $data['end_time'] = $data['end_time']['text'];
        return $data;
    }

    /**
     * 获取未结束的数据列表
     */
    public function getLinkDatas()
    {
        return $this->where('status', '=', 0)
            ->where('is_delete', '=', 0)
            ->where('end_time', '>', time())
            ->select();
    }
}